<?php
declare (strict_types=1);

namespace app\admin\logic\market;

use app\admin\logic\system\Log;
use app\admin\model\market\VipConfig as VipConfigModel;
use app\common\exception\LogicException;

/**
 * vip模型
 */
class VipConfig extends VipConfigModel
{
    /**
     * 获取列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-20
     *
     * @return   [type]                         [description]
     */
    public function getList(array $map = [])
    {
        $map['mhm_id'] = request()->mhm_id;

        return $this->where($map)->order('update_time', 'DESC')->paginate($this->getListRows());
    }

    /**
     * 创建vip配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-20
     *
     * @param array $data [description]
     * @return   [type]                               [description]
     */
    public function createVipConfig(array $data)
    {
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        $data['mhm_id'] = request()->mhm_id;
        // 创建成功
        if (!$this->save($data)) {
            throw new LogicException('创建失败');
        }

        Log::write('新建会员等级【' . $data['title'] . '】', 'user_vip', 'create', true);

        // 返回值
        return $this;
    }

    /**
     * 编辑vip配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-20
     *
     * @param    [type]                         $id   [description]
     * @param    [type]                         $data [description]
     * @return   [type]                               [description]
     */
    public function editVipConfig($id, $data)
    {
        $vip = $this->where('id', $id)->findOrFail();

        $check       = $data;
        $check['id'] = $id;
        // 验证数据
        $this->getValidate()->scene('edit')->failException()->check($check);

        $vip->title          = $data['title'];
        $vip->days           = $data['days'];
        $vip->scribing_price = $data['scribing_price'];
        $vip->price          = $data['price'];
        $vip->give_credit    = $data['give_credit'];
        $vip->give_days      = $data['give_days'];
        if (!$vip->save()) {
            throw new LogicException('更新失败');
        }

        Log::write('更新会员等级【' . $data['title'] . '】', 'user_vip', 'update', true);

        return $vip;
    }

    /**
     * 删除vip配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-20
     *
     * @param    [type]                         $id [description]
     * @return   [type]                             [description]
     */
    public function deleteVipConfig($id)
    {
        $vip = $this->where('id', $id)->findOrFail();

        if (!$vip->delete()) {
            throw new LogicException("删除失败");
        }

        Log::write('删除会员等级【' . $vip->title . '】', 'user_vip', 'delete', true);
    }
}
